import { useCallback, useState } from "react";
import { Button, Checkbox, Form, Input, message } from "antd";
import styled from "styled-components";
import { loginAPI } from "@/api/login";
import { useNavigate, useLocation, useSearchParams } from "react-router-dom";
import { lStorage } from "@/utils/storage";
import { flushSync } from "react-dom";
import { setToken } from "@/utils/auth/index";
import { useDispatch, useSelector } from "react-redux";
import action from "@/store/action/index";
import useMyContext from "@/hooks/useContext";

import { addDynamicRoutes } from "@/router/index2";
import routes from "@/router/routes2";
import { cloneDeep } from "lodash";

const AccountStyled = styled.div`
  .ant-form-item-control-input-content {
    display: flex;
    justify-content: space-between;
  }
`;

// 自定义校验规则
const validator = {
  username(_, value) {
    if (value.length === 0) return Promise.reject("请输入用户名");
    return Promise.resolve();
  },
  password(_, value) {
    if (value.length === 0) return Promise.reject("请输入密码");
    if (value.length < 5) return Promise.reject("请输入至少5位密码");
    return Promise.resolve();
  },
};

const Account = (props) => {
  const defaultRoutes = cloneDeep(routes);
  const dispatch = useDispatch();
  const [search] = useSearchParams();
  const navigate = useNavigate();
  const { openMessage, messageApi } = useMyContext();
  const permissionStore = useSelector((state) => state.permission);

  const [formIns] = Form.useForm();

  //loading实例
  const [loading, setLoading] = useState(false);

  const isRemember = lStorage.get("isRemember") || false;

  const submit = async () => {
    await formIns.validateFields(); //触发校验
    const { username, password, isRemember } = formIns.getFieldsValue();

    //具体的登录方法
    const doLogin = async (username, password) => {
      flushSync(() => {
        setLoading(true);
        openMessage("loading", "正在验证...", "loading");
      });
      // 登录前触发校验
      try {
        let res = await loginAPI({ username, password });

        messageApi.destroy("loading"); //销毁验证消息实例
        if (res.code !== 0) {
          throw new Error(res.message);
        }
        openMessage("success", "登录成功！");

        // 持久化token
        setToken(res.data.token);
        //获取用户信息
        await dispatch(action.user.getUserInfo());
        //获取博客信息
        await dispatch(action.app.getBlogInfo());
        //记住我功能
        if (isRemember) {
          lStorage.set("isRemember", isRemember);
          lStorage.set("loginInfo", { username, password }); //前端用户输入表单的数据，非后端
        } else {
          lStorage.remove("loginInfo");
          lStorage.remove("isRemember");
        }

        //动态添加路由，完整的路由表
        let newRoutes = await addDynamicRoutes(defaultRoutes);
        //更新redux中的路由表
        dispatch(action.permission.setCompleteRoutes({ routes: newRoutes }));

        //处理登录页登录成功跳转
        if (search.get("redirect")) {
          const path = search.get("redirect");

          navigate(
            {
              pathname: path,
            },
            { replace: true }
          );
        } else {
          navigate("/home", { replace: true }); //默认push
        }
      } catch (error) {
        openMessage("error", "请重新输入用户名和密码！");
      } finally {
        // 无论成功失败都将loading关闭
        setLoading(false);
      }
    };

    if (JSON.parse(process.env.REACT_APP_USE_CAPTCHA)) {
      //是否需要验证码，后登录
    } else {
      doLogin(username, password);
    }
  };

  //默认值
  let loginInfo = {
    username: "test@qq.com",
    password: "11111",
  };

  const initLoginInfo = useCallback(() => {
    //获取本地存储信息填充表单
    const localLoginInfo = lStorage.get("loginInfo");
    if (localLoginInfo) {
      loginInfo = {
        username: localLoginInfo?.username || "test@qq.com",
        password: localLoginInfo?.password || "11111",
      };
    }
  }, []);

  initLoginInfo();

  return (
    <AccountStyled>
      <Form
        form={formIns}
        name="Account"
        labelCol={{
          span: 8,
        }}
        //默认值
        initialValues={{
          isRemember: isRemember,
          username: loginInfo.username,
          password: loginInfo.password,
        }}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          validateTrigger="onBlur"
          rules={[
            {
              required: true,
              validator: validator.username,
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              validator: validator.password,
            },
          ]}
          validateTrigger="onBlur"
        >
          <Input.Password />
        </Form.Item>

        <Form.Item>
          <Form.Item name="isRemember" valuePropName="checked" noStyle>
            <Checkbox>记住我</Checkbox>
          </Form.Item>

          <a
            className="login-form-forgot"
            style={{ color: "#316C72FF" }}
            href="http://"
          >
            忘记密码
          </a>
        </Form.Item>

        <Form.Item
          style={{
            width: "100%",
          }}
        >
          <Button
            style={{ width: "100%", height: "40px" }}
            type="primary"
            onClick={submit}
            loading={loading}
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </AccountStyled>
  );
};

export default Account;
